package org.jeecg.modules.syncdata.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.jeffreyning.mybatisplus.service.MppServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.ApiSignUtil;
import org.jeecg.modules.syncdata.entity.SyncLog;
import org.jeecg.modules.syncdata.mapper.SyncLogMapper;
import org.jeecg.modules.syncdata.service.SyncLogService;
import org.jeecg.modules.syncdata.service.SyncService;
import org.jeecg.modules.thirdpartyapi.constant.BgApiEnum;
import org.jeecg.modules.thirdpartyapi.dto.SyncLogDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 同步日志服务实现类
 *
 * @author zhanglei01
 * @date 2022/03/16
 */
@Slf4j
@Service
public class SyncLogServiceImpl extends MppServiceImpl<SyncLogMapper, SyncLog>
        implements SyncLogService {

    @Autowired
    private SyncService syncService;

    private static final String API_NAME = "getSyncLog";

    @Override
    public Boolean getSyncResult(String tableName, String dayTime) {
        SyncLog syncLog = new SyncLog();
        syncLog.setSyncTable(tableName);
        syncLog.setDayTime(dayTime);
        SyncLog log = selectByMultiId(syncLog);
        if (log == null || log.getFinishStatus().equals(0)) {
            return false;
        }
        return true;
    }

    @Override
    public Boolean setSyncFinish(String tableName, String dayTime, Boolean isSuccess) {
        return setSyncFinish(tableName, dayTime, isSuccess, null);
    }

    @Override
    public Boolean setSyncFinish(String tableName, String dayTime, Boolean isSuccess, String msg) {
        SyncLog syncLog = new SyncLog();
        syncLog.setSyncTable(tableName);
        syncLog.setDayTime(dayTime);
        if (isSuccess) {
            syncLog.setFinishStatus(1);
        } else {
            syncLog.setFinishStatus(0);
        }
        syncLog.setEndTime(new Date());
        syncLog.setMsg(msg);
        SyncLog selectSyncLog = selectByMultiId(syncLog);
        if (selectSyncLog != null) {
            boolean b = updateByMultiId(syncLog);
            syncLog.setStartTime(selectSyncLog.getStartTime());
            syncLogPush(syncLog);
            return b;
        }
        boolean save = save(syncLog);
        syncLogPush(syncLog);
        return save;
    }

    @Override
    public Boolean setSyncStart(String tableName, String dayTime) {
        SyncLog syncLog = new SyncLog();
        syncLog.setSyncTable(tableName);
        syncLog.setDayTime(dayTime);
        syncLog.setFinishStatus(0);
        syncLog.setStartTime(new Date());
        SyncLog log = selectByMultiId(syncLog);
        if (log != null) {
            if (log.getStartTime() != null) {
                return true;
            }
            return updateByMultiId(syncLog);
        }
        return save(syncLog);
    }

    @Override
    public Boolean getSyncResultExceptOrder(String dayTime) {
        Integer syncResultExceptOrder = getBaseMapper().getSyncResult(dayTime, "1");
        //去掉两个order表
        int length = BgApiEnum.values().length - 2;
        if (syncResultExceptOrder.equals(length)) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean getBeforeDaySyncResult(String dayTime) {
        //先判断前一天
        String yesterday = DateUtil.offsetDay(DateUtil.parse(dayTime), -1).toDateStr();
        Integer syncResult = getBaseMapper().getSyncResult(yesterday, null);
        Boolean yesterdayFlag = false;
        //第一次同步
        if (syncResult.equals(0)) {
            yesterdayFlag = true;
        }
        int length = BgApiEnum.values().length;
        if (syncResult.equals(length)) {
            yesterdayFlag = true;
        }
        //判断当天
        Boolean syncResultExceptOrder = getSyncResultExceptOrder(dayTime);
        if (yesterdayFlag && syncResultExceptOrder) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean getSyncResult(String dayTime) {
        Integer syncResult = getBaseMapper().getSyncResult(dayTime, null);
        int length = BgApiEnum.values().length;
        if (syncResult.equals(length)) {
            return true;
        }
        return false;
    }

    @Override
    public List<SyncLog> getSyncFailData(Integer pageSize) {
        return getBaseMapper().getSyncFailData();
    }

    @Override
    public DateTime getSyncDateTime(String tableName) {
        String lastSyncDateTime = getBaseMapper().getLastSyncDateTime(tableName);
        //如果没有获取到，说明第一次同步，同步昨天
        if (StringUtils.isBlank(lastSyncDateTime)) {
            return DateUtil.yesterday();
        }
        //判断如果是在昨天前，返回下一天
        DateTime parse = DateUtil.parse(lastSyncDateTime);
        if (parse.isAfterOrEquals(DateUtil.beginOfDay(DateUtil.yesterday()))) {
            return DateUtil.yesterday();
        }
        return DateUtil.offsetDay(parse, 1);
    }

    @Override
    public IPage<SyncLog> getSyncDataList(String updateTime, Integer indexPage) {
        Page<SyncLog> page = new Page<>(indexPage,5);
        return getBaseMapper().getSyncDataList(page,updateTime);
    }

    private void syncLogPush(SyncLog syncLog) {
        try {
            SyncLogDto syncLogDto = new SyncLogDto();
            syncLogDto.setLogType("sync_log");
            String gzip = ApiSignUtil.gzip(JSONArray.toJSONString(Arrays.asList(syncLog)));
            syncLogDto.setDataMsg(gzip);
            syncService.callThirdPartyApiUnUpGzip(API_NAME, syncLogDto);
        } catch (Exception e) {
            log.error("调用api:{} 异常", API_NAME, e);
        }
    }
}
